package com.zhaopin.theswordreferstooffer;

/**
 * @author yin.peide
 * @date 2021-06-09 11:28
 * 面试题14： 调整数组顺序使奇数位于偶数前面
 */
public class Offer14 {

    public static void main(String[] args) {

        int[] aAttr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        int[] retAttr = Solution14.exchange(aAttr);
        for (int i : retAttr) {
            System.out.print(i + " ");
        }

        System.out.println();


    }

}

class Solution14 {

    public static int[] exchange(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }

        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            //如果是奇数，就往后挪，直到遇到偶数为止 //此处判断偶数奇数逻辑可以抽象出来
            while (left < right && isUnEven(nums[left])) {
                left++;
            }
            //如果是偶数，就往前挪，直到遇到奇数为止 //此处判断偶数奇数逻辑可以抽象出来
            while (left < right && isEven(nums[right])) {
                right--;
            }
            //交换两个值
            if (left < right) {
                int tmp1 = nums[right];
                int tmp2 = nums[left];

                nums[left] = tmp1;
                nums[right] = tmp2;
            }
        }
        return nums;
    }


    /**
     * 是偶数
     *
     * @return
     */
    public static boolean isEven(int n) {
        return (n & 1) == 0;
    }

    /**
     * 是奇数
     *
     * @param n
     * @return
     */
    public static boolean isUnEven(int n) {
        return (n & 1) == 1;
    }

}
